package top.mhtools.pigeon.common.service.support;

import com.google.common.collect.Maps;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import top.mhtools.pigeon.common.config.ApplicationContextHolder;
import top.mhtools.pigeon.common.exception.ServiceException;

import java.util.Map;
import java.util.Objects;

/**
 * 消息通知执行策略
 *
 * @author machen
 * @date 2020/4/24 19:24
 */
@Component
public class SendMessageExecuteChooser implements ApplicationRunner {

    private Map<String, AbstractSendMessageExecuteStrategy> chooseMap = Maps.newHashMap();

    public AbstractSendMessageExecuteStrategy choose(String type) {
        AbstractSendMessageExecuteStrategy result = chooseMap.get(type);
        if (Objects.isNull(result)) {
            throw new ServiceException("请输入正确的消息平台");
        }
        return result;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        ApplicationContext applicationContext = ApplicationContextHolder.get();
        Map<String, AbstractSendMessageExecuteStrategy> solverMap = applicationContext.getBeansOfType(AbstractSendMessageExecuteStrategy.class);
        solverMap.values().forEach(each -> chooseMap.put(each.supports(), each));
    }
}
